package com.ruoyi.develop.lvRuku.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.function.Supplier;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.uuid.IdUtils;

import javax.annotation.Resource;

import com.ruoyi.constants.BusinessConstants;
import com.ruoyi.develop.goodsOrderIn.domain.GoodsOrderIn;
import com.ruoyi.develop.goodsOrderIn.service.IGoodsOrderInService;
import com.ruoyi.develop.goodsSupplier.domain.GoodsSupplier;
import com.ruoyi.develop.goodsSupplier.service.IGoodsSupplierService;
import com.ruoyi.develop.lvRukumingxi.domain.LvRukumingxi;
import com.ruoyi.develop.lvRukumingxi.mapper.LvRukumingxiMapper;
import com.ruoyi.develop.lvRukumingxi.service.ILvRukumingxiService;
import com.ruoyi.develop.produceRecord.domain.ProduceRecord;
import com.ruoyi.develop.produceRecord.mapper.ProduceRecordMapper;
import com.ruoyi.develop.produceRecordDetail.domain.ProduceRecordDetail;
import com.ruoyi.develop.produceRecordDetail.mapper.ProduceRecordDetailMapper;
import org.springframework.stereotype.Service;
import com.ruoyi.develop.lvRuku.mapper.LvRukuMapper;
import com.ruoyi.develop.lvRuku.domain.LvRuku;
import com.ruoyi.develop.lvRuku.service.ILvRukuService;

/**
 * 入库单Service业务层处理
 *
 * @author qh
 * @date 2024-09-12
 */
@Service
public class LvRukuServiceImpl implements ILvRukuService {
    @Resource
    private LvRukuMapper lvRukuMapper;
    @Resource
    private ILvRukumingxiService rukumingxiService;
    @Resource
    private IGoodsOrderInService goodsOrderInService;
    @Resource
    private ProduceRecordMapper produceRecordMapper;
    @Resource
    private ProduceRecordDetailMapper produceRecordDetailMapper;
    @Resource
    private IGoodsSupplierService iGoodsSupplierService;
    @Resource
    private LvRukumingxiMapper lvRukumingxiMapper;




    /**
     * 查询入库单
     *
     * @param id 入库单主键
     * @return 入库单
     */
    @Override
    public LvRuku selectById(String id) {
        return lvRukuMapper.selectById(id);
    }

    /**
     * 查询入库单列表
     *
     * @param entity 入库单
     * @return 入库单
     */
    @Override
    public List<LvRuku> selectList(LvRuku entity) {
        return lvRukuMapper.selectList(entity);
    }

    @Override
    public String selectMaxCode(String today) {
        return lvRukuMapper.selectMaxCode(today);
    }

    /**
     * 新增入库单
     *
     * @param entity 入库单
     * @return 结果
     */
    @Override
    public int insert(LvRuku entity) {
        if (StringUtils.isBlank(entity.getId())) {
            entity.setId(IdUtils.fastSimpleUUID());
        }
        entity.setCreateBy(SecurityUtils.getUsername());
        entity.setCreateTime(DateUtils.getNowDate());
        return lvRukuMapper.insert(entity);
    }


    /**
     * 新增入库单 带明细
     *
     * @param entity 入库单 带明细
     * @return 结果
     */
    @Override
    public int insertWithDetail(LvRuku entity) {
        if (StringUtils.isBlank(entity.getId())) {
            entity.setId(IdUtils.fastSimpleUUID());
        }
        String supplierName="";
        if(StringUtils.isNotBlank(entity.getSupplierId())){
            GoodsSupplier supplier=iGoodsSupplierService.selectById(entity.getSupplierId());
            if(supplier!=null){
                supplierName=supplier.getName();
            }
        }
        entity.setSupplierName(supplierName);
        entity.setCreateBy(SecurityUtils.getUsername());
        entity.setCreateTime(DateUtils.getNowDate());
        setMaxCode(entity);
        lvRukuMapper.insert(entity);
        List<LvRukumingxi> details = entity.getDetailList();
        for (LvRukumingxi detail : details) {
            detail.setParentId(entity.getId());
            detail.setType(entity.getType());
            detail.setRukuno(entity.getNos());
            detail.setRukudate(entity.getRukuDate());
            detail.setNos(entity.getNos());
            detail.setSupplierId(entity.getSupplierId());
            detail.setSupplierName(supplierName);
            detail.setStatus(BusinessConstants.STORAGE_STATE_YES);
            detail.setSource(entity.getSource());
            if(detail.getDun()==null){
                detail.setDun(BigDecimal.ZERO);
            }
            detail.setRukuren(entity.getRukupeople());
            if (StringUtils.isBlank(detail.getGoodsId())) {
                continue;
            }
            LvRukumingxi lvRukumingxiBeginMoney=lvRukumingxiMapper.selectBeginMoney();
            if("0".equals(entity.getType())){
                detail.setBeginMoney(lvRukumingxiBeginMoney.getBeginMoney().add(detail.getGoodsBuyTotal()));
            }else if("1".equals(entity.getType())){
                detail.setBeginMoney(lvRukumingxiBeginMoney.getBeginMoney().subtract(detail.getGoodsBuyTotal()));
            }

            rukumingxiService.insert(detail);
            updateGoodsOrderInByMingxiAdd(detail);
        }
        return 1;
    }


    public void setMaxCode(LvRuku entity) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String today = sdf.format(entity.getRukuDate() == null ? new Date() : entity.getRukuDate());
        String codeMaxString = this.selectMaxCode(today);
        if (StringUtils.isNotBlank(codeMaxString)) {
            // 最大编号+1
            codeMaxString = Long.parseLong(codeMaxString) + 1 + "";
        } else {
            codeMaxString = today + "0001";
        }
        entity.setNos(codeMaxString);
    }


    /**
     * 修改入库单
     *
     * @param entity 入库单
     * @return 结果
     */
    @Override
    public int update(LvRuku entity) {
        entity.setUpdateBy(SecurityUtils.getUsername());
        entity.setUpdateTime(DateUtils.getNowDate());
        return lvRukuMapper.update(entity);
    }

    /**
     * 修改入库单 带着明细
     *
     * @param entity 入库单
     * @return 结果
     */
    @Override
    public int updateWithDetail(LvRuku entity) {
        String supplierName="";
        if(StringUtils.isNotBlank(entity.getSupplierId())){
            GoodsSupplier supplier=iGoodsSupplierService.selectById(entity.getSupplierId());
            if(supplier!=null){
                supplierName=supplier.getName();
            }
        }
        entity.setSupplierName(supplierName);
        entity.setUpdateBy(SecurityUtils.getUsername());
        entity.setUpdateTime(DateUtils.getNowDate());

        // 先删除明细  更新 库存
        LvRukumingxi rukumingxi = new LvRukumingxi();
        rukumingxi.setParentId(entity.getId());
        List<LvRukumingxi> oldDetails = rukumingxiService.selectList(rukumingxi);
        for (LvRukumingxi detail : oldDetails) {
            updateGoodsOrderInByMingxiDelete(detail);
            rukumingxiService.deleteByIdPhysical(detail.getId());
        }
        List<LvRukumingxi> details = entity.getDetailList();
        for (LvRukumingxi detail : details) {
            detail.setParentId(entity.getId());
            detail.setType(entity.getType());
            detail.setRukuno(entity.getNos());
            detail.setRukudate(entity.getRukuDate());
            detail.setNos(entity.getNos());
            detail.setSupplierId(entity.getSupplierId());
            detail.setSupplierName(supplierName);
            detail.setStatus("1");
            detail.setSource(entity.getSource());
            if(detail.getDun()==null){
                detail.setDun(BigDecimal.ZERO);
            }
            detail.setRukuren(entity.getRukupeople());
            if (StringUtils.isBlank(detail.getGoodsId())) {
                continue;
            }
            rukumingxiService.insert(detail);
            // 更新库存
            updateGoodsOrderInByMingxiAdd(detail);
        }

        return lvRukuMapper.update(entity);
    }


    public void updateGoodsOrderInByMingxiAdd(LvRukumingxi detail) {
        GoodsOrderIn goodsOrderIn = goodsOrderInService.selectById(detail.getGoodsId());
        if (detail.getType().equals(BusinessConstants.TYPE_RUKU)) {
            goodsOrderIn.setCount(goodsOrderIn.getCount().add(detail.getDaohuoCount()));
            goodsOrderIn.setDun(goodsOrderIn.getDun().add(detail.getDun()));
            goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount().add(detail.getDaohuoCount()));
        }
        if (detail.getType().equals(BusinessConstants.TYPR_CHUKU)) {
            goodsOrderIn.setCount(goodsOrderIn.getCount().subtract(detail.getDaohuoCount()));
            goodsOrderIn.setDun(goodsOrderIn.getDun().subtract(detail.getDun()));
            goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount().subtract(detail.getDaohuoCount()));
        }
        goodsOrderInService.update(goodsOrderIn);
    }

    public void updateGoodsOrderInByMingxiDelete(LvRukumingxi detail) {
        GoodsOrderIn goodsOrderIn = goodsOrderInService.selectById(detail.getGoodsId());
        if (detail.getType().equals(BusinessConstants.TYPR_CHUKU)) {
            goodsOrderIn.setCount(goodsOrderIn.getCount().add(detail.getDaohuoCount()));
            goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount().add(detail.getDaohuoCount()));
        }
        if (detail.getType().equals(BusinessConstants.TYPE_RUKU)) {
            goodsOrderIn.setCount(goodsOrderIn.getCount().subtract(detail.getDaohuoCount()));
            goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount().subtract(detail.getDaohuoCount()));
        }
        goodsOrderInService.update(goodsOrderIn);
    }

    /**
     * 批量删除入库单
     *
     * @param ids 需要删除的入库单主键
     * @return 结果
     */
    @Override
    public int deleteByIds(String[] ids) {
        for (String id : ids) {
            LvRukumingxi rukumingxi = new LvRukumingxi();
            rukumingxi.setParentId(id);
            List<LvRukumingxi> oldDetails = rukumingxiService.selectList(rukumingxi);
            for (LvRukumingxi detail : oldDetails) {
                updateGoodsOrderInByMingxiDelete(detail);
                rukumingxiService.deleteById(detail.getId());
            }
        }
        return lvRukuMapper.deleteByIds(ids);
    }

    /**
     * 删除入库单信息
     *
     * @param id 入库单主键
     * @return 结果
     */
    @Override
    public int deleteById(String id) {
        LvRukumingxi rukumingxi = new LvRukumingxi();
        rukumingxi.setParentId(id);
        List<LvRukumingxi> oldDetails = rukumingxiService.selectList(rukumingxi);
        for (LvRukumingxi detail : oldDetails) {
            updateGoodsOrderInByMingxiDelete(detail);
            rukumingxiService.deleteById(detail.getId());
        }
        return lvRukuMapper.deleteById(id);
    }


    /**
     * 根据生产单入库
     */
    @Override
    public void rukuByProduce(ProduceRecord produceRecord, List<ProduceRecordDetail> list) {
        LvRuku ruku = new LvRuku();
        ruku.setId(IdUtils.fastSimpleUUID());
        ruku.setCreateBy(SecurityUtils.getUsername());
        ruku.setCreateTime(new Date());
        ruku.setProduceRecordId(produceRecord.getId());
        ruku.setProduceRecordNos(produceRecord.getNos());
        ruku.setSource(BusinessConstants.RUKU_SOURCE_PRODUCE);
        ruku.setType(BusinessConstants.TYPE_RUKU);
        ruku.setStatus(BusinessConstants.STORAGE_STATE_YES);
        ruku.setRukuDate(new Date());
        setMaxCode(ruku);
        lvRukuMapper.insert(ruku);
        produceRecord.setRukuId(ruku.getId());
        produceRecordMapper.update(produceRecord);

        // 设置入库明细
        for (ProduceRecordDetail detail : list) {
            LvRukumingxi rukumingxi = new LvRukumingxi();
            rukumingxi.setGoodsId(detail.getGoodsId());
            rukumingxi.setCode(detail.getGoodsCode());
            rukumingxi.setGoodsName(detail.getGoodsName());
            rukumingxi.setGoodsModel(detail.getGoodsModel());
            rukumingxi.setRukudate(ruku.getRukuDate());
            rukumingxi.setUnit(detail.getGoodsUnit());
            rukumingxi.setNos(ruku.getNos());
            rukumingxi.setParentId(ruku.getId());
            rukumingxi.setDaohuoCount(detail.getCount());
            rukumingxi.setRukuno(ruku.getNos());
            rukumingxi.setRukudate(ruku.getRukuDate());
            rukumingxi.setRukuren(ruku.getRukupeople());
            rukumingxi.setParentId(ruku.getId());
            rukumingxi.setType(BusinessConstants.TYPE_RUKU);
            rukumingxi.setRukuren(SecurityUtils.getUsername());
            rukumingxi.setProduceRecordId(produceRecord.getId());
            rukumingxi.setProduceRecordNos(produceRecord.getNos());
            rukumingxi.setProduceRecordDetailId(detail.getId());
            rukumingxi.setDouser(detail.getDouser());
            rukumingxi.setDoremark(detail.getDoremark());
            rukumingxi.setIsdo(BusinessConstants.STATUS_YES);
            rukumingxi.setStatus("1");
            rukumingxi.setIsZhijian("1");
            rukumingxi.setSort(detail.getSort());
            rukumingxiService.insert(rukumingxi);
            detail.setRukuId(ruku.getId());
            detail.setRukuDetailId(rukumingxi.getId());
            produceRecordDetailMapper.update(detail);
            // 更新库存信息
            GoodsOrderIn goodsOrderIn = goodsOrderInService.selectById(detail.getGoodsId());
            if (goodsOrderIn != null) {
                goodsOrderIn.setCount(goodsOrderIn.getCount().add(detail.getCount()));
                goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount().add(detail.getCount()));
                goodsOrderInService.update(goodsOrderIn);
            }
        }
    }

    /**
     * 根据生产单 出库
     */
    @Override
    public void chukuByProduce(ProduceRecord produceRecord, List<ProduceRecordDetail> list) {
        LvRuku ruku = new LvRuku();
        ruku.setId(IdUtils.fastSimpleUUID());
        ruku.setCreateBy(SecurityUtils.getUsername());
        ruku.setCreateTime(new Date());
        ruku.setProduceRecordId(produceRecord.getId());
        ruku.setProduceRecordNos(produceRecord.getNos());
        ruku.setSource(BusinessConstants.RUKU_SOURCE_PRODUCE);
        ruku.setType(BusinessConstants.TYPR_CHUKU);
        ruku.setRukuDate(new Date());
        setMaxCode(ruku);
        lvRukuMapper.insert(ruku);
        // 设置入库明细
        for (ProduceRecordDetail detail : list) {
            LvRukumingxi rukumingxi = new LvRukumingxi();
            rukumingxi.setGoodsId(detail.getGoodsId());
            rukumingxi.setGoodsName(detail.getGoodsName());
            rukumingxi.setGoodsModel(detail.getGoodsModel());
            rukumingxi.setRukudate(ruku.getRukuDate());
            rukumingxi.setUnit(detail.getGoodsUnit());
            rukumingxi.setNos(ruku.getNos());
            rukumingxi.setParentId(ruku.getId());
            rukumingxi.setDaohuoCount(detail.getCount());
            rukumingxi.setRukuno(ruku.getNos());
            rukumingxi.setRukudate(ruku.getRukuDate());
            rukumingxi.setRukuren(ruku.getRukupeople());
            rukumingxi.setParentId(ruku.getId());
            rukumingxi.setType(BusinessConstants.TYPR_CHUKU);
            rukumingxi.setRukuren(SecurityUtils.getUsername());
            rukumingxi.setProduceRecordId(produceRecord.getId());
            rukumingxi.setProduceRecordNos(produceRecord.getNos());
            rukumingxi.setProduceRecordDetailId(detail.getId());
            rukumingxi.setDouser(detail.getDouser());
            rukumingxi.setDoremark(detail.getDoremark());
            rukumingxi.setIsZhijian("1");
            rukumingxiService.insert(rukumingxi);
            // 更新库存信息
            GoodsOrderIn goodsOrderIn = goodsOrderInService.selectById(detail.getGoodsId());
            if (goodsOrderIn != null) {
                goodsOrderIn.setCount(goodsOrderIn.getCount().subtract(detail.getCount()));
                goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount().subtract(detail.getCount()));
                goodsOrderInService.update(goodsOrderIn);
            }
        }
    }

    /**
     * 根据生产明细 出库
     */
    @Override
    public void chukuByProduceDetail(ProduceRecordDetail detail) {
        LvRukumingxi rukumingxi = new LvRukumingxi();
        rukumingxi.setProduceRecordDetailId(detail.getId());
        LvRukumingxi rukudetail = rukumingxiService.selectById(detail.getRukuDetailId());
        rukumingxiService.deleteById(rukudetail.getId());
        // 更新库存信息
        GoodsOrderIn goodsOrderIn = goodsOrderInService.selectById(rukudetail.getGoodsId());
        if (goodsOrderIn != null) {
            goodsOrderIn.setCount(goodsOrderIn.getCount().subtract(rukudetail.getDaohuoCount()));
            goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount().subtract(rukudetail.getDaohuoCount()));
            goodsOrderInService.update(goodsOrderIn);
        }
    }

    /**
     * 根据生产明细 入库
     */
    @Override
    public void rukuByProduceDetail(ProduceRecordDetail detail, ProduceRecord produceRecord) {
        String rukuId = produceRecord.getRukuId();
        LvRuku ruku = lvRukuMapper.selectById(rukuId);
        if(ruku!=null){
            ruku.setStatus(BusinessConstants.STORAGE_STATE_YES);
            lvRukuMapper.update(ruku);
        }
        LvRukumingxi rukumingxi = new LvRukumingxi();
        rukumingxi.setGoodsId(detail.getGoodsId());
        rukumingxi.setGoodsName(detail.getGoodsName());
        rukumingxi.setGoodsModel(detail.getGoodsModel());
        rukumingxi.setRukudate(ruku.getRukuDate());
        rukumingxi.setUnit(detail.getGoodsUnit());
        rukumingxi.setNos(ruku.getNos());
        rukumingxi.setParentId(ruku.getId());
        rukumingxi.setDaohuoCount(detail.getCount());
        rukumingxi.setRukuno(ruku.getNos());
        rukumingxi.setRukudate(ruku.getRukuDate());
        rukumingxi.setRukuren(ruku.getRukupeople());
        rukumingxi.setParentId(ruku.getId());
        rukumingxi.setType(BusinessConstants.TYPE_RUKU);
        rukumingxi.setRukuren(SecurityUtils.getUsername());
        rukumingxi.setProduceRecordId(produceRecord.getId());
        rukumingxi.setProduceRecordNos(produceRecord.getNos());
        rukumingxi.setProduceRecordDetailId(detail.getId());
        rukumingxi.setDouser(detail.getDouser());
        rukumingxi.setDoremark(detail.getDoremark());
        rukumingxi.setIsdo(BusinessConstants.STATUS_YES);
        rukumingxi.setIsZhijian(BusinessConstants.INSPECT_STATE_YES);
        rukumingxi.setStatus(BusinessConstants.STORAGE_STATE_YES);
        rukumingxiService.insert(rukumingxi);

        detail.setRukuDetailId(rukumingxi.getId());
        produceRecordDetailMapper.update(detail);
        // 更新库存信息
        GoodsOrderIn goodsOrderIn = goodsOrderInService.selectById(detail.getGoodsId());
        if (goodsOrderIn != null) {
            goodsOrderIn.setCount(goodsOrderIn.getCount().add(detail.getCount()));
            goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount().add(detail.getCount()));
            goodsOrderInService.update(goodsOrderIn);
        }
    }

    @Override
    public void oneKeyBuyOut(LvRuku lvRuku) {
        LvRuku newRuku = new LvRuku();
        BeanUtils.copyProperties(lvRuku, newRuku, "id");
        newRuku.setId(IdUtils.fastSimpleUUID());
        newRuku.setCreateBy(SecurityUtils.getUsername());
        newRuku.setCreateTime(new Date());
        newRuku.setSource(BusinessConstants.RUKU_SOURCE_BUY);
        newRuku.setType(BusinessConstants.TYPR_CHUKU);
        newRuku.setRukuDate(new Date());
        newRuku.setMoney(lvRuku.getMoney());
//        newRuku.set
        setMaxCode(newRuku);
        lvRukuMapper.insert(newRuku);
        LvRukumingxi rukumingxi = new LvRukumingxi();
        rukumingxi.setParentId(lvRuku.getId());
        List<LvRukumingxi> rukumingxiList = rukumingxiService.selectList(rukumingxi);
        for (LvRukumingxi detail : rukumingxiList) {
            detail.setCanCount(BigDecimal.ZERO);
            LvRukumingxi newDetail = new LvRukumingxi();
            BeanUtils.copyProperties(detail, newDetail, "id");
            newDetail.setNos(newRuku.getNos());
            newDetail.setRukudate(newRuku.getRukuDate());
            newDetail.setParentId(newRuku.getId());
            newDetail.setRukuno(newRuku.getNos());
            newDetail.setType(BusinessConstants.TYPR_CHUKU);
            newDetail.setRukuren(SecurityUtils.getUsername());
            rukumingxiService.insert(newDetail);
            rukumingxiService.update(detail);
            // 更新库存信息
            GoodsOrderIn goodsOrderIn = goodsOrderInService.selectById(detail.getGoodsId());
            if (goodsOrderIn != null) {
                goodsOrderIn.setCount(goodsOrderIn.getCount().subtract(detail.getDaohuoCount()));
                goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount().subtract(detail.getDaohuoCount()));
                goodsOrderInService.update(goodsOrderIn);
            }
        }

        lvRuku.setOutFlag(BusinessConstants.STATUS_YES);
        lvRukuMapper.update(lvRuku);

    }


}
